Throw and Throws Keywords
In Java, the throw and throws keywords are used to handle exceptions explicitly. While they sound similar, they serve different purposes:
throw: Used to explicitly throw an exception within a method.throws: Used in a method signature to declare that a method might pass an exception to the caller.
In this section, weβll explore:
- The syntax and usage of
throwandthrows. - Practical examples of throwing and declaring exceptions.
- Key differences between
throwandthrows.
1. The throw Keywordβ
The throw keyword is used to explicitly throw an exception within a method. It allows you to create and throw custom exceptions or rethrow existing ones.
Syntax of throwβ
throw new ExceptionType("Error message");
Example: Throwing a Custom Exceptionβ
public class ThrowExample {
public static void validateAge(int age) {
if (age < 18) {
throw new ArithmeticException("Age must be 18 or above.");
} else {
System.out.println("Valid age.");
}
}
public static void main(String[] args) {
try {
validateAge(16); // This will throw an exception
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
Error: Age must be 18 or above.
Explanation:
- The
validateAgemethod throws anArithmeticExceptionif the age is less than 18. - The
catchblock in themainmethod handles the exception.
2. The throws Keywordβ
The throws keyword is used in a method signature to declare that a method might throw one or more exceptions. It delegates the responsibility of handling the exception to the caller.
Syntax of throwsβ
public void methodName() throws ExceptionType {
// Code that might throw an exception
}
Example: Declaring Checked Exceptionsβ
import java.io.FileReader;
import java.io.FileNotFoundException;
public class ThrowsExample {
public static void readFile(String fileName) throws FileNotFoundException {
FileReader file = new FileReader(fileName); // This may throw FileNotFoundException
}
public static void main(String[] args) {
try {
readFile("nonExistentFile.txt");
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
Error: nonExistentFile.txt (No such file or directory)
Explanation:
- The
readFilemethod declares that it might throw aFileNotFoundExceptionusing thethrowskeyword. - The caller (
mainmethod) is responsible for handling the exception using atry-catchblock.
Key Differences Between throw and throwsβ
| Aspect | throw | throws |
|---|---|---|
| Purpose | Used to explicitly throw an exception. | Used to declare that a method might throw an exception. |
| Location | Inside a method body. | In the method signature. |
| Applies To | A single exception instance. | One or more exception types. |
| Example | throw new ArithmeticException("Error"); | public void method() throws IOException |
Best Practices for Using throw and throwsβ
-
Use
throwfor Explicit Errors:- Use
throwto signal specific error conditions, especially when validating input or enforcing business rules.
public static void checkBalance(double balance) {
if (balance < 0) {
throw new IllegalArgumentException("Balance cannot be negative.");
}
} - Use
-
Declare Checked Exceptions with
throws:- Always declare checked exceptions in the method signature using
throwsso that callers are aware of potential exceptions.
public void connectToDatabase() throws SQLException {
// Code to connect to the database
} - Always declare checked exceptions in the method signature using
-
Avoid Overusing
throwsfor Runtime Exceptions:- Runtime exceptions (unchecked exceptions) do not need to be declared using
throws. Overusingthrowsfor unchecked exceptions can clutter the code.
- Runtime exceptions (unchecked exceptions) do not need to be declared using
-
Provide Meaningful Error Messages:
- When throwing exceptions, include descriptive error messages to aid debugging.
throw new NullPointerException("Attempted to access a null object.");
Practical Example: Combining throw and throwsβ
Hereβs an example that combines both throw and throws:
import java.io.FileReader;
import java.io.FileNotFoundException;
public class CombinedExample {
public static void readFile(String fileName) throws FileNotFoundException {
if (fileName == null || fileName.isEmpty()) {
throw new IllegalArgumentException("File name cannot be null or empty.");
}
FileReader file = new FileReader(fileName); // This may throw FileNotFoundException
}
public static void main(String[] args) {
try {
readFile(""); // This will throw IllegalArgumentException
} catch (IllegalArgumentException | FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
Error: File name cannot be null or empty.
Explanation:
- The
readFilemethod usesthrowto validate the file name andthrowsto declare theFileNotFoundException. - The
mainmethod handles both exceptions using a multi-catch block.
Key Takeawaysβ
- The
throwkeyword is used to explicitly throw an exception within a method. - The
throwskeyword is used in a method signature to declare that a method might throw one or more exceptions. throwis used inside the method body, whilethrowsis used in the method signature.- Best practices include providing meaningful error messages, declaring checked exceptions, and avoiding overuse of
throwsfor runtime exceptions.